package com.taiji.dicom4platform.common.security.filter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.taiji.dicom4platform.common.model.entity.SysUser;
import com.taiji.dicom4platform.common.security.model.CommonUserDetails;
import com.taiji.dicom4platform.common.security.service.IUserDetailService;
import com.taiji.dicom4platform.common.security.service.TokenService;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

/**
 * @Description
 * @Author fanxl
 * @Date 2021/5/19
 **/
@AllArgsConstructor
public class AuthenticationFilter extends OncePerRequestFilter {

    private TokenService tokenService;
    private IUserDetailService iUserDetailService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = tokenService.getHearToken(request);
        if(StrUtil.isNotEmpty(token)){
            String username = tokenService.getUserName(token);
            SysUser sysUser = iUserDetailService.getByUsername(username);
            CommonUserDetails userDetails = new CommonUserDetails();
            BeanUtil.copyProperties(sysUser,userDetails);
            Collection<? extends GrantedAuthority> authorities =  iUserDetailService.getUserInfo(sysUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, authorities);
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }
}
